package com.plant.pay.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.alipay.easysdk.factory.Factory;
import com.plant.pay.domain.PayVo;
import com.plant.pay.service.WxPayService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/pay")
@RestController
public class  PayController {
    @Autowired
    private WxPayService wxPayService;
    @GetMapping("/checkWx/{orderId}")
    public String checkWxOrder(@PathVariable String orderId) throws Exception {
        //1.根据订单号,去微信中,查询订单状态
        Map<String, String> checkMap = wxPayService.queryNative(orderId);
        //2.获取请求结果
        String return_code = checkMap.get("return_code");
        if (return_code.equals("SUCCESS")) {
            //3.获取订单状态
            String trade_state = checkMap.get("trade_state");
            if (trade_state.equals("SUCCESS")) {
                // 订单已经支付
                // 修改订单状态(修改数据库中的订单状态)
            } else if (trade_state.equals("PAYERROR")) {
                // 支付失败!
                // 修改订单状态(修改数据库中的订单状态);
            } else if (trade_state.equals("CLOSED")) {
                // 订单超时,已关闭!
                // 修改订单状态(修改数据库中的订单状态);
            } else if (trade_state.equals("NOTPAY")) {
                // 未支付!
            } else if (trade_state.equals("USERPAYING")) {
                // 支付中!
            } else if (trade_state.equals("REFUND")) {
                // 已取消
            }
            return trade_state;
        } else {
            // 获取请求失败原因
            String return_msg = checkMap.get("return_msg");
            throw new RuntimeException(return_msg);
        }
    }
    @PostMapping("/subWx")
    public String subWxOrder(@RequestBody PayVo payVo) throws Exception {
        //1.从数据库查询(订单名称,订单编号,订单金额)
        String body = payVo.getTitle();    //订单名称(商品名称)
        String orderId = payVo.getOrderId();   //订单编号
        String money = "1";         //订单金额(分)
        //3.调用微信工具类,把订单发给微信
        Map<String, String> payMap = wxPayService.createNative(body, orderId, money);
        if (payMap == null) {
            throw new RuntimeException("下单失败,请稍后重试!");
        }
        //4.判断下单是否正常
        String return_code = payMap.get("return_code");
        if (!return_code.equals("SUCCESS")) {
            //获取错误信息
            String return_msg = payMap.get("return_msg");
            throw new RuntimeException(return_msg);
        }
        //5.如果成功,则获取生成的支付Url
        String code_url = payMap.get("code_url");
        return code_url;
    }

    @RequestMapping("/zfb")
    public String paymoney(@RequestBody PayVo payVo) throws AlipayApiException {
        System.out.println(payVo);
        String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDe0CdRpSZM18uEaaDQEbe60XlQRBUCWAjz8K+V2/wdkyrBxe/8mQv6QZrwL/5MpL6saWolLO1kPZUpzb9ODOiK8GJG9KWvMVnAsd++KytiDZ5SsjXMMbQrMtsaJBl5orESCH9AWxZun8D6JeWM6Vl++rssLe/atEL+gUSccRtEFDQ/wW3Z2pacHPEc4Kt0FE9g/HryIWmcSosXd4gREhjl1mNmfmrQx48p6S+xEURNxHM1wIYi4uy/CMx8PoPCYFbxP+6idq2klJRT4C7h4gYpYEnbZ+iyJ1rdF1ZyEt648EUcptAWGA9yexzrboqch1ZT3gZPgo4bOknw3ZgCIv4ZAgMBAAECggEAA8b1k63AC3dxDMqZnk1elv0sGE8/J+4EINaIs3qqOHohNG29lsOlb1WjYcT+g6AbV2LmGME9OQDOQYoqXxFa89gFYnyNPn4QrnKVf2zN7HicoXxB6zdAfab8DeJkyCoY5Fxeg+HHbJKqu9LepFfkW4G2oJYaxdNee2AHoLtOIgZJjoEwm4KzBJ9UzNftjqsTbabC6Uzxgr/tWWjMBX+KH7ch5ZP/O4p+EkJw5cMzVdaK9QuGaM98wVvBAqPWTIPOsvIqfSWtZFMAu7Fx+f5yEa6IxdJ2z7jm55GwbtL6azf3eIgM7b1t0b1WZl5Drvn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9GBb4akWA+n9T/d22L9+EzBHsh1NCaD3WfYqzddARC4ahFs+XyrMYjTJppH5U+XhaxxX1wK2XL4kV3wBZC7MTX7w22Cg3RMc5o2Buh07iR13VmOzUuZz9EcnVUoGiiIilYW2eO7BgZPB82BwhcFRhYv73Wd9Ekq1a+2drKhbkatHLuZtsPBVSN+JTWdjjmESl1s+atTkTFSQ4Tuc/eT7/Uj86BRsSpzl5dJjA9tCpDnwIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000140607726");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl("http://hjl789.w1.luyouxia.net/pay/notify");
        request.setReturnUrl(payVo.getUrl());
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        if(payVo.getOrderId()!=null && !payVo.getOrderId().equals("")){
            model.setOutTradeNo(payVo.getOrderId());
        }
        if(payVo.getOrdersId()!=null && !payVo.getOrdersId().equals("")){
            model.setOutTradeNo(payVo.getOrdersId());
        }
        if(payVo.getConId()!=null && !payVo.getConId().equals("")){
            model.setOutTradeNo(payVo.getConId());
        }
        model.setTotalAmount(payVo.getMoney());
        model.setSubject(payVo.getTitle());
        model.setProductCode("QUICK_WAP_WAY");
        model.setSellerId("2088721041615706");
        request.setBizModel(model);
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return pageRedirectionData;
    }


    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单状态
            }
        }
        return "success";
    }

    }


